package org.madgecko.basic.controller;

import org.madgecko.basic.util.SecurityUtil;
import org.madgecko.basic.model.*;
import org.madgecko.basic.service.iface.*;
import org.madgecko.web.CommandContext;
import org.madgecko.web.PropertyHolder;
import org.madgecko.web.SessionContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AdminController {

	@Inject
	private IUserService userService;
	@Inject
	private IRoleService roleService;
	@Inject
	private IModuleService moduleService;
	@Inject
	private ICommandService commandService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String rootPage(){
        return "login";
    }

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginPage(){
		return "login";
	}

    @RequestMapping("/admin")
    public String adminPage(HttpSession session){
        User user = (User)session.getAttribute("user");
        if(user!=null){
            return "admin/admin";
        }
        return "login";
    }

    @RequestMapping("/admin/header")
    public String headerPage(){
        return "admin/header";
    }

	@ResponseBody
	@RequestMapping(value = "/loginRequest", method = RequestMethod.POST, produces={"application/json; charset=UTF-8"})
	public Object loginRequest(String username, String pwd,  HttpSession session){
		try {
            User u = userService.loadByName(username);
            if(u==null){
                return new ExtReturn(false, null, "用户名或密码错误");
            }
            // 验证密码
            String pagePwd = SecurityUtil.md5(pwd);
            if(!u.getPassword().equals(pagePwd)){
                return new ExtReturn(false, null, "用户名或密码错误");
            }
            // 为当前会话session存入属性user
            session.setAttribute("user", u);
            // 增加登录用户的session到CmsSessionContext以排除swfupload丢失session的bug
            SessionContext.addSession(session);
            return new ExtReturn(true, "teacher");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return new ExtReturn(false);
		}
	}

	@ResponseBody
	@RequestMapping(value = "/initTeacherAuthority", produces={"application/json; charset=UTF-8"})
	public Object initTeacherAuthority(HttpSession session){
		User currentUser = (User)session.getAttribute("user");
		Map<String, Object> authorityMap = new HashMap<String, Object>();
		authorityMap.put("user", currentUser);

		boolean ifDevelopModel = PropertyHolder.getBooleanProperty("develop.model");
		// develop model使用root用户的权限
		if(ifDevelopModel==true){
			authorityMap.put("userModule", moduleService.listAllModule());
			authorityMap.put("userCommand", commandService.listAllCommand());
		}else{
			if(currentUser.getUsername().equals("root")){
				//root user init
				authorityMap.put("userModule", moduleService.listAllModule());
				authorityMap.put("userCommand", commandService.listAllCommand());
			}else{
				//normal user init
				List<Role> roles = roleService.listRoleByUser(currentUser.getId());
				List<Integer> roleIds = new ArrayList<Integer>();
				for(Role r : roles){
					roleIds.add(r.getId());
				}
				List<Command> commands = commandService.listCommandByRoles(roleIds);
				List<Module> modules = moduleService.listModuleByRoles(roleIds);
				CommandContext.addUserCommand(session.getId(), convertCommands2Str(commands));
				SessionContext.addSession(session);
				authorityMap.put("userModule", modules);
				authorityMap.put("userCommand", commands);
			}
		}
		// 不将initTeacherAuthority的工作放入login方法的原因是，login方法返回登录结果、不能直接返回权限，
		// 若将authorityMap存入用户的session,则占用内存较多，
		// 采用2次请求，第一次请求返回登录结果，第二次请求返回用户权限。
		return new ExtReturn(true, authorityMap);
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session){
		SessionContext.removeSession(session.getId());
		CommandContext.removeUserCommand(session.getId());
		session.invalidate();
		return "redirect:/index";
	}

	private String convertCommands2Str(List<Command> commands){
		String str = "|";
		for(Command c : commands){
			str += c.getUrl() + "|";
		}
		return str;
	}

}
